﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Configuration.Provider;

namespace newtelligence.DasBlog.Web.Core
{
    public class SiteSecurityMembershipProvider : MembershipProvider
    {
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
        }

        public override string ApplicationName
        {
            get;
            set;
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            UserToken token = SiteSecurity.Login(username, oldPassword);
            if (token != null)
            {
                SiteSecurity.SetPassword(username, newPassword);
            }
            return true;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new ProviderException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (SiteSecurity.GetUser(username) != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }
            else if (SiteSecurity.GetUserByEmail(email) != null)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            SiteSecurity.AddUser(username, password, "contrib", false, email);
            status = MembershipCreateStatus.Success;
            return new MembershipUser("dasBlog", username, username, email, null, null, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            SiteSecurity.DeleteUser(username);
            return true;
        }

        public override bool EnablePasswordReset
        {
            get { return false; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            if (string.IsNullOrEmpty(emailToMatch))
                return new MembershipUserCollection();

            MembershipUserCollection users = new MembershipUserCollection();
            int count = 0;
            foreach (User user in SiteSecurity.GetUsers())
            {
                if (string.Compare(user.EmailAddress,emailToMatch,true) == 0 )
                {
                    count++;

                    if (count < pageIndex * pageSize || count >= (pageIndex + 1) * pageSize)
                        continue;

                    users.Add(
                        new MembershipUser(
                            "dasBlog",
                            user.Name,
                            user.Name,
                            user.EmailAddress,
                            null,
                            user.DisplayName,
                            user.Active,
                            !user.Active,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now));
                }
            }
            totalRecords = count;
            return users;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            int count = 0;
            foreach (User user in SiteSecurity.GetUsers())
            {
                if (user.Name == usernameToMatch)
                {
                    count++;

                    if (count < pageIndex * pageSize || count >= (pageIndex + 1) * pageSize)
                        continue;

                    users.Add(new MembershipUser(
                            "dasBlog",
                            user.Name,
                            user.Name,
                            user.EmailAddress,
                            null,
                            user.DisplayName,
                            user.Active,
                            !user.Active,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now));
                }
            }
            totalRecords = count;
            return users;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            int count = 0;
            foreach (User user in SiteSecurity.GetUsers())
            {
                count++;

                if (count < pageIndex * pageSize || count >= (pageIndex + 1) * pageSize)
                    continue;

                users.Add(new MembershipUser(
                            "dasBlog",
                            user.Name,
                            user.Name,
                            user.EmailAddress,
                            null,
                            user.DisplayName,
                            user.Active,
                            !user.Active,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now));
            
            }
            totalRecords = count;
            return users;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new ProviderException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new ProviderException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            User user = SiteSecurity.GetUser(username);
            if (user != null)
            {
                return new MembershipUser(
                            "dasBlog",
                            user.Name,
                            user.Name,
                            user.EmailAddress,
                            null,
                            user.DisplayName,
                            user.Active,
                            !user.Active,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now,
                            DateTime.Now);                       
            }
            else
            {
                throw new ProviderException();
            }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return GetUser((string)providerUserKey, userIsOnline);
        }

        public override string GetUserNameByEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
                return null;

            User user = SiteSecurity.GetUserByEmail(email);
            if (user != null)
            {
                return user.Name;
            }
            else
            {
                return null;
            }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return int.MaxValue; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 0; }
        }

        public override int PasswordAttemptWindow
        {
            get { return int.MaxValue; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Clear; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return null; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new ProviderException();
        }

        public override bool UnlockUser(string userName)
        {
            User user = SiteSecurity.GetUser(userName);
            if (user != null)
            {
                user.Active = true;
                SiteSecurity.UpdateUser(user);
            }
            else
            {
                throw new ProviderException();
            }
            return true;
        }

        public override void UpdateUser(MembershipUser member)
        {
            User user = SiteSecurity.GetUser(member.UserName);
            if (user != null)
            {
                user.DisplayName = member.Comment;
                user.EmailAddress = member.Email;
                user.Active = member.IsLockedOut;
                SiteSecurity.UpdateUser(user);
            }
            else
            {
                throw new ProviderException();
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            return SiteSecurity.GetUserToken(username, password) != null;
        }
    }
}
